package com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.repository.HddcCollecteddrillholeNativeRepository;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.repository.HddcCollecteddrillholeRepository;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.repository.entity.HddcCollecteddrillholeEntity;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.service.HddcCollecteddrillholeService;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.viewobjects.HddcCollecteddrillholePageVO;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.viewobjects.HddcCollecteddrillholeQueryParams;
import com.css.zfzx.sjcj.modules.hddcCollectedDrillHole.viewobjects.HddcCollecteddrillholeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 钻探调查数据-钻孔-点管理
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcCollecteddrillholeServiceImpl implements HddcCollecteddrillholeService {

    private final HddcCollecteddrillholeRepository hddcCollecteddrillholeRepository;
    private final HddcCollecteddrillholeNativeRepository hddcCollecteddrillholeNativeRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcCollecteddrillholeServiceImpl(HddcCollecteddrillholeRepository hddcCollecteddrillholeRepository,
                                             HddcCollecteddrillholeNativeRepository hddcCollecteddrillholeNativeRepository,
                                             ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcCollecteddrillholeRepository = hddcCollecteddrillholeRepository;
        this.hddcCollecteddrillholeNativeRepository = hddcCollecteddrillholeNativeRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcCollecteddrillholes(HddcCollecteddrillholeQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcCollecteddrillholePageVO> hddcCollecteddrillholePage = this.hddcCollecteddrillholeNativeRepository.queryHddcCollecteddrillholes(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcCollecteddrillholePage);
    }


    @Override
    public HddcCollecteddrillholeEntity getHddcCollecteddrillhole(String id) {
        return this.hddcCollecteddrillholeRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcCollecteddrillholeEntity saveHddcCollecteddrillhole(HddcCollecteddrillholeEntity hddcCollecteddrillhole) {
        String uuid = UUIDGenerator.getUUID();
        hddcCollecteddrillhole.setUuid(uuid);
        hddcCollecteddrillhole.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcCollecteddrillhole.setCreateTime(now);
        hddcCollecteddrillhole.setUpdateTime(now);
        hddcCollecteddrillhole.setIsValid(PlatformConstants.Y);
        hddcCollecteddrillhole.setQualityinspectionStatus(PlatformConstants.N);
        hddcCollecteddrillhole.setExtends10(PlatformConstants.Y);
        this.hddcCollecteddrillholeRepository.save(hddcCollecteddrillhole);
        return hddcCollecteddrillhole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcCollecteddrillholeEntity updateHddcCollecteddrillhole(HddcCollecteddrillholeEntity hddcCollecteddrillhole) {
        HddcCollecteddrillholeEntity entity = hddcCollecteddrillholeRepository.findById(hddcCollecteddrillhole.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcCollecteddrillhole);
        hddcCollecteddrillhole.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcCollecteddrillhole.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcCollecteddrillholeRepository.save(hddcCollecteddrillhole);
        return hddcCollecteddrillhole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcCollecteddrillholes(List<String> ids) {
        List<HddcCollecteddrillholeEntity> hddcCollecteddrillholeList = this.hddcCollecteddrillholeRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcCollecteddrillholeList) && hddcCollecteddrillholeList.size() > 0) {
            for(HddcCollecteddrillholeEntity hddcCollecteddrillhole : hddcCollecteddrillholeList) {
                hddcCollecteddrillhole.setIsValid(PlatformConstants.N);
                hddcCollecteddrillhole.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcCollecteddrillhole.setUpdateTime(new Date());
                this.hddcCollecteddrillholeRepository.save(hddcCollecteddrillhole);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcCollecteddrillholeQueryParams queryParams, HttpServletResponse response) {
        List<HddcCollecteddrillholeEntity> yhDisasterEntities = hddcCollecteddrillholeNativeRepository.exportYhDisasters(queryParams);
        List<HddcCollecteddrillholeVO> list=new ArrayList<>();
        for (HddcCollecteddrillholeEntity entity:yhDisasterEntities) {
            HddcCollecteddrillholeVO yhDisasterVO=new HddcCollecteddrillholeVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"收集钻孔-点","收集钻孔-点",HddcCollecteddrillholeVO.class,"收集钻孔-点.xls",response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcCollecteddrillholeVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcCollecteddrillholeVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcCollecteddrillholeVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcCollecteddrillholeVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcCollecteddrillholeVO> list) {
        for (HddcCollecteddrillholeVO hddcCollecteddrillholeVO : list) {
            HddcCollecteddrillholeEntity yhDisasterEntity = new HddcCollecteddrillholeEntity();
            BeanUtils.copyProperties(hddcCollecteddrillholeVO, yhDisasterEntity);
            saveHddcCollecteddrillhole(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcCollecteddrillholeEntity> hddcCollecteddrillholeList = this.hddcCollecteddrillholeRepository.queryHddcCollecteddrillholesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcCollecteddrillholeList) && hddcCollecteddrillholeList.size() > 0) {
            for(HddcCollecteddrillholeEntity hddcCollecteddrillhole : hddcCollecteddrillholeList) {
                hddcCollecteddrillhole.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcCollecteddrillhole.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcCollecteddrillhole.setIsValid(PlatformConstants.N);
                this.hddcCollecteddrillholeRepository.save(hddcCollecteddrillhole);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcCollecteddrillholeEntity> hddcCollecteddrillholeList = this.hddcCollecteddrillholeRepository.queryHddcCollecteddrillholesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcCollecteddrillholeList) && hddcCollecteddrillholeList.size() > 0) {
            for(HddcCollecteddrillholeEntity hddcCollecteddrillhole : hddcCollecteddrillholeList) {
                hddcCollecteddrillhole.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcCollecteddrillhole.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcCollecteddrillhole.setIsValid(PlatformConstants.N);
                this.hddcCollecteddrillholeRepository.save(hddcCollecteddrillhole);
            }
        }
    }

}
